<template>
  <div class="container" ref="container">
    <div class="search-keyword">
      <span>搜索 歌曲/歌单</span>
      <span class="keyword">"{{ keyword }}"</span>
    </div>
    <Loader class="loading" v-if="loading" />
    <div v-else class="list">
      <SongItem :songInfo="songInfo" v-for="(songInfo, i) in songList" :key="i" />
    </div>
    <div class="pagination-container">
      <n-pagination v-model:page="pageConfig.currentPage" :page-count="pageConfig.pageCount" simple :on-update:page="updateList" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();

const keyword = ref('');
const loading = ref(true);
onMounted(async () => {
  keyword.value = route.query.keyword;
  getResult();
});
watch(
  () => route.query.keyword,
  (newKeyword) => {
    keyword.value = newKeyword || '';
    getResult();
  }
);

const container = ref(null);
const songList = ref([]);
async function getResult() {
  if (!keyword.value) {
    loading.value = false;
    return;
  }
  loading.value = true;
  if (container.value) {
    container.value.scrollTo({ top: 0, behavior: 'smooth' });
  }
  const res = await window.BiliAPI.typeSearch(keyword.value, pageConfig.currentPage);
  loading.value = false;
  songList.value = res.result;
  pageConfig.pageCount = res.numPages;
}

const pageConfig = reactive({
  currentPage: 1,
  pageCount: 1,
});
function updateList(currentPage) {
  pageConfig.currentPage = currentPage;
  getResult();
}
</script>

<style scoped lang="scss">
.container {
  height: calc(100vh - 70px - 120px - 40px);
  overflow: auto;
  padding-left: 15px;

  .search-keyword {
    font-size: 26px;
    font-weight: 700;
    color: #878787;

    .keyword {
      color: #000;
    }
  }

  .loading {
    position: relative;
    height: calc(100vh - 120px);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .list {
    margin: 20px 0;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }
}
</style>
